<template>
  <div class="setting">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <el-button type="primary" icon="el-icon-plus" @click="showAdd">新增角色</el-button>
            <el-table
              v-loading="loading"
              :data="list"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                align="center"
                label="序号"
                width="180"
                :index="indexMethod"
              />
              <el-table-column
                prop="name"
                label="角色名"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                label="操作"
              >
                <template v-slot="{ row }">
                  <el-button type="text" @click="assignPer(row.id)">分配权限</el-button>
                  <el-button type="text" @click="edit(row)">修改</el-button>
                  <el-button type="text" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row style="height: 50px;" type="flex" justify="end" align="middle">
              <!--
              total: 总数量
              page-size: 每页的数量  分页组件会自动计算有多少页
              current-page: 当前页时第几页
            -->
              <el-pagination
                background
                layout="total, sizes,prev, pager, next, jumper"
                :total="total"
                :page-size="pagesize"
                :current-page="page"
                :page-sizes="[5, 10, 15, 20]"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </el-row>

            <el-dialog :title="form.id?'编辑角色':'添加角色'" :visible="showDialog" @close="close">
              <el-form ref="form" :model="form" :rules="rules">
                <el-form-item prop="name" label="角色名称">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item prop="description" label="角色描述">
                  <el-input v-model="form.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-row type="flex" justify="center">
                  <el-button @click="showDialog = false">取消</el-button>
                  <el-button type="primary" @click="addRole">确定</el-button>
                </el-row>
              </template>
            </el-dialog>
          </el-tab-pane>
          <!-- 公司信息 -->
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input disabled style="width:400px" :value="company.name" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input disabled style="width:400px" :value="company.companyAddress" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input disabled style="width:400px" :value="company.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" :rows="3" disabled style="width:400px" :value="company.remarks" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible.sync="showAssignDialog">
        <!-- 内容部分 -->
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          :data="permissions"
          :props="defaultProps"
          :show-checkbox="true"
          :default-expand-all="true"
          :check-strictly="true"
          node-key="id"
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showAssignDialog = false">取消</el-button>
            <el-button type="primary" @click="addPermission">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleList, deleteRole, addRole, updateRole, getCompany } from '@/api/settings'
import { getAllPermissions, assignPrem } from '@/api/permisson'
import { getUserRole } from '@/api/user'
import { listTotree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    const validateName = async(rule, value, callback) => {
      // 获取所有记录条数
      const res = await getRoleList(1, this.total)
      res.rows.some(item => item === value) ? callback(new Error('添加的角色名已经存在')) : callback()
    }
    return {
      activeName: 'role',
      list: [],
      page: 1,
      pagesize: 5,
      total: 0,
      loading: false,
      showDialog: false,
      company: {},
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      showAssignDialog: false,
      userId: '',
      permissions: [],
      defaultProps: {
        label: 'name'
      },
      treeLoading: false
    }
  },
  watch: {
    async activeName() {
      const companyId = this.$store.state.user.userInfo.companyId
      if (this.activeName === 'company') {
        const res = await getCompany(companyId)
        // console.log(res)
        this.company = res
      }
    }
  },
  created() {
    this.getRoles()
    this.getAllPermissions()
  },
  methods: {
    async getRoles() {
      this.loading = true
      const res = await getRoleList(this.page, this.pagesize)
      // console.log(res)
      this.list = res.rows
      this.total = res.total
      this.loading = false
    },
    handleCurrentChange(value) {
      this.page = value
      this.getRoles()
    },
    handleSizeChange(value) {
      this.pagesize = value
      // 页码重置为1  因为如果当前页码是最后一页 直接把每页显示的数据设置为最大条数不够显示的会导致 没有数据显示
      this.page = 1
      this.getRoles()
    },
    // 处理的是每页显示的序号
    indexMethod(index) { // index  0
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 删除功能__________________________________________________
    async del(id) {
      try {
        await this.$confirm('确认删除该角色吗')
      } catch {
        return false
      }
      await deleteRole(id)
      this.getRoles()
      // 当当前页面数据还剩一条 数据 此时删除时会导致页面不跳转到第一页
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.$message.success('删除角色成功')
    },
    showAdd() {
      this.showDialog = true
    },
    close() {
      this.showDialog = false
      // 重置表单数据
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 添加功能__________________________________________________
    async addRole() {
      try {
        await this.$refs.form.validate()
      } catch {
        return false
      }
      if (this.form.id) {
        await updateRole(this.form)
        this.showDialog = false
        this.getRoles()
        this.$message.success('编辑角色成功')
      } else {
        await addRole(this.form)
        // 关闭弹框
        this.showDialog = false
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        this.getRoles(this.page, this.pagesize)
        this.$message.success('添加角色成功')
      }
    },
    // 编辑模块__________________________________________________
    edit(row) {
      this.showDialog = true
      this.form = { ...row } // 只不过这样子获取的数据不是最新的数据
    },
    // handleClick(value) {
    // console.log(value.name)
    // if (value.name === 'company') {
    // }
    // console.log(this.activeName)
    // }
    // 分配权限
    async assignPer(id) {
      this.treeLoading = true
      this.showAssignDialog = true
      this.userId = id
      const { permIds } = await getUserRole(this.userId)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
      this.treeLoading = false
    },
    async getAllPermissions() {
      const res = await getAllPermissions()
      // console.log(res, '------')
      this.permissions = listTotree(res, '0')
    },
    // 确定修改权限分配  // 分配权限
    async addPermission() {
      await assignPrem({
        id: this.userId,
        permIds: this.$refs.tree.getCheckedKeys() // element ui 提供
      })
      this.$message.success('分配权限成功')
      this.showAssignDialog = false
    }

  }
}
</script>

<style>

</style>
